package leetcode10;

import java.util.ArrayList;
import java.util.List;

public class test54 {
    /**
     * 39. 组合总和
     * @param candidates
     * @param target
     * @return
     */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> list = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        back(list,path,candidates,target,0,0);
        return list;
    }
    public void back(List<List<Integer>> list,List<Integer> path,int[] candidates,int target,int sum,int index){
        if(sum == target){
            list.add(new ArrayList<>(path));
        }
        for(int i = index;i < candidates.length;i++){
            if(sum > target)break;
            path.add(candidates[i]);
            sum += candidates[i];
            back(list,path,candidates,target,sum,i);
            path.removeLast();
            sum -= candidates[i];
        }
    }
}
